package com.tutorial.bf.processor;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.lang.reflect.Proxy;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 时间日志功能增强
 *
 * @ClassName TimeLogBeanPostProcessor
 * @Description 时间日志功能增强
 * @Author G
 * @Date 2025/3/14 14:59
 */
public class TimeLogBeanPostProcessor implements BeanPostProcessor {


    /**
     * Apply this {@code BeanPostProcessor} to the given new bean instance <i>before</i> any bean
     * initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
     * or a custom init-method). The bean will already be populated with property values.
     * The returned bean instance may be a wrapper around the original.
     * <p>The default implementation returns the given {@code bean} as-is.
     *
     * @param bean     the new bean instance
     * @param beanName the name of the bean
     * @return the bean instance to use, either the original or a wrapped one;
     * if {@code null}, no subsequent BeanPostProcessors will be invoked
     * @throws BeansException in case of errors
     * @see InitializingBean#afterPropertiesSet
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Object beanProxy = Proxy.newProxyInstance(bean.getClass().getClassLoader(), bean.getClass().getInterfaces(), (proxy, method, args) -> {
            // 1、输出开始时间
            System.out.println("方法：" + method.getName() + "-开始时间：" + dateFormat.format(new Date()));
            // 2、执行目标方法
            Object result = method.invoke(bean, args);
            // 3、输出结束时间
            System.out.println("方法：" + method.getName() + "-结束时间：" + dateFormat.format(new Date()));
            return result;
        });
        return beanProxy;
    }
}
